<!-- src/views/Chat/ChatContainer.vue -->
<script setup>
import {ref, computed, onMounted, onUnmounted, nextTick, watch} from 'vue';
import { io } from 'socket.io-client';
import axios from 'axios';
import { useRouter } from 'vue-router';
import ChatHeader from './ChatHeader.vue';
import Sidebar from './Sidebar.vue';
import ChatArea from './ChatArea.vue';
import Notification from './Notification.vue';

const router = useRouter();

// 用户状态
const currentUser = ref('');
const currentUserInitial = ref('');
const onlineUsers = ref([]);
const selectedUser = ref('');
const searchQuery = ref('');
const newMessage = ref('');
const allMessages = ref({});
const notification = ref({
  show: false,
  message: ''
});
const showLogoutConfirmation = ref(false);

// Socket 和定时器
const socket = ref(null);
const heartbeatTimer = ref(null);

// 计算属性
const filteredUsers = computed(() => {
  if (!searchQuery.value) return onlineUsers.value;
  return onlineUsers.value.filter(user =>
      user.username.toLowerCase().includes(searchQuery.value.toLowerCase()))
});

const onlineCount = computed(() => {
  return onlineUsers.value.filter(user => user.online).length;
});

const messages = computed(() => {
  return selectedUser.value && allMessages.value[selectedUser.value]
      ? [...allMessages.value[selectedUser.value]]
      : [];
});

// 用户选择处理
const handleSelectUser = (username) => {
  selectedUser.value = username;
  if (!allMessages.value[username]) {
    allMessages.value[username] = [];
  }
  loadMessages();
};

// 显示通知
const showNotification = (msg) => {
  notification.value = {
    show: true,
    message: msg
  };

  setTimeout(() => {
    notification.value.show = false;
  }, 3000);
};

// 用户头像首字母
const userInitial = (username) => {
  return username ? username.charAt(0) : '';
};

// 时间格式化
const formatTime = (timeStr, format = 'YYYY-MM-DD HH:mm') => {
  const date = new Date(timeStr);

  if (isNaN(date)) {
    console.error('Invalid date:', timeStr);
    return '0000-00-00 00:00';
  }

  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');

  return format
      .replace('YYYY', year)
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hours)
      .replace('mm', minutes);
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const container = document.querySelector('.message-container');
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  });
};

// 获取并更新在线用户列表
const updateOnlineUsers = async () => {
  try {
    const response = await axios.get('api/online_users', {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });

    const onlineList = response.data.online_users || [];

    // 更新在线状态
    onlineUsers.value = onlineUsers.value.map(user => ({
      ...user,
      online: onlineList.includes(user.username)
    }));

    // 添加新用户
    onlineList.forEach(username => {
      if (username !== currentUser.value &&
          !onlineUsers.value.some(u => u.username === username)) {
        onlineUsers.value.push({
          username: username,
          online: true
        });
      }
    });

  } catch (error) {
    console.error('获取在线用户失败:', error);
    showNotification('获取在线用户失败');
  }
};

// 初始化Socket连接
const initSocket = () => {
  const token = localStorage.getItem('token');
  if (!token) return;

  try {
    socket.value = io('http://127.0.0.1:5000', {
      extraHeaders: {
        Authorization: `Bearer ${token}`
      },
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
    });

    // 监听连接成功事件
    socket.value.on('connect', () => {
      console.log('Socket connected');
      socket.value.emit('join_room', currentUser.value);
      startHeartbeat();
      updateOnlineUsers();
    });

    // 监听初始在线状态事件
    socket.value.on('initial_online_status', (data) => {
      const onlineList = data.online_users || [];
      onlineUsers.value = onlineUsers.value.map(user => ({
        ...user,
        online: onlineList.includes(user.username)
      }));

      onlineList.forEach(username => {
        if (username !== currentUser.value &&
            !onlineUsers.value.some(u => u.username === username)) {
          onlineUsers.value.push({
            username: username,
            online: true
          });
        }
      });
    });

    // 监听用户状态更新事件
    socket.value.on('user_status', (data) => {
      const userIndex = onlineUsers.value.findIndex(u => u.username === data.username);
      if (userIndex !== -1) {
        onlineUsers.value[userIndex].online = data.online;
      } else if (data.username !== currentUser.value) {
        onlineUsers.value.push({
          username: data.username,
          online: data.online
        });
      }
    });

    // 监听新消息事件
    socket.value.on('new_message', (msg) => {
      if (msg.receiver === currentUser.value || msg.sender === currentUser.value) {
        const otherUser = msg.sender === currentUser.value ? msg.receiver : msg.sender;

        if (!allMessages.value[otherUser]) {
          allMessages.value[otherUser] = [];
        }

        const isDuplicate = allMessages.value[otherUser].some(
            m => m.id === msg.id || (m.content === msg.content && m.timestamp === msg.timestamp)
        );

        if (!isDuplicate) {
          allMessages.value[otherUser].push(msg);
          allMessages.value[otherUser].sort((a, b) =>
              new Date(a.timestamp) - new Date(b.timestamp));

          if (selectedUser.value === otherUser) {
            scrollToBottom();
          }

          if (msg.sender !== currentUser.value && selectedUser.value !== otherUser) {
            showNotification(`${msg.sender} 发来了新消息`);
          }
        }
      }
    });

    // 错误处理
    socket.value.on('connect_error', (err) => {
      console.error('Socket连接错误:', err);
      showNotification('连接服务器失败，请检查网络');
    });

    socket.value.on('disconnect', () => {
      console.log('Socket disconnected');
      stopHeartbeat();
      showNotification('连接已断开，正在尝试重新连接...');
    });

    socket.value.on('reconnect', () => {
      console.log('Socket reconnected');
      startHeartbeat();
      updateOnlineUsers();
      showNotification('连接已恢复');
    });

  } catch (error) {
    console.error('初始化Socket失败:', error);
    showNotification('连接服务器失败');
  }
};

// 心跳检测
const startHeartbeat = () => {
  stopHeartbeat();
  heartbeatTimer.value = setInterval(() => {
    axios.post('api/heartbeat', {}, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    }).catch(error => {
      console.warn('心跳检测失败:', error);
    });
  }, 10000);
};

const stopHeartbeat = () => {
  if (heartbeatTimer.value) {
    clearInterval(heartbeatTimer.value);
    heartbeatTimer.value = null;
  }
};

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await axios.get('api/users', {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });

    onlineUsers.value = response.data
        .filter(user => user.username !== currentUser.value)
        .map(user => ({
          username: user.username,
          online: false
        }));

    await updateOnlineUsers();

  } catch (error) {
    console.error('获取用户列表失败:', error);
    showNotification('获取用户列表失败');
  }
};

// 加载历史消息
const loadMessages = async () => {
  if (!selectedUser.value) return;

  try {
    const response = await axios.get(`api/messages?with=${selectedUser.value}`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (!allMessages.value[selectedUser.value]) {
      allMessages.value[selectedUser.value] = [];
    }

    const existingIds = new Set(allMessages.value[selectedUser.value].map(m => m.id));
    const newMessages = response.data.filter(msg => !existingIds.has(msg.id));

    allMessages.value[selectedUser.value].push(...newMessages);
    allMessages.value[selectedUser.value].sort((a, b) =>
        new Date(a.timestamp) - new Date(b.timestamp));

    scrollToBottom();

  } catch (error) {
    console.error('加载消息失败:', error);
    showNotification('加载消息失败');
  }
};

// 发送消息
const sendMessage = () => {
  if (!newMessage.value.trim() || !selectedUser.value) {
    showNotification('消息不能为空');
    return;
  }

  if (!socket.value || !socket.value.connected) {
    showNotification('连接已断开，请刷新页面');
    return;
  }

  socket.value.emit('send_message', {
    receiver: selectedUser.value,
    content: newMessage.value.trim()
  });

  // 本地立即显示发送的消息
  // const newMsg = {
  //   sender: currentUser.value,
  //   receiver: selectedUser.value,
  //   content: newMessage.value.trim(),
  //   timestamp: new Date().toISOString()
  // };
  //
  // if (!allMessages.value[selectedUser.value]) {
  //   allMessages.value[selectedUser.value] = [];
  // }
  //
  // allMessages.value[selectedUser.value].push(newMsg);

  // 重新加载信息
  loadMessages()

  newMessage.value = '';
  scrollToBottom();
};

// 退出登录
const logout = () => {
  localStorage.removeItem('token');
  stopHeartbeat();

  if (socket.value) {
    try {
      if (socket.value.connected) {
        socket.value.disconnect();
      }
    } catch (error) {
      console.warn('安全断开连接时出错:', error);
    } finally {
      socket.value = null;
    }
  }

  router.push('/login');
};


// 添加侧边栏可见状态
const sidebarVisible = ref(false);

// 在移动端切换侧边栏
const toggleSidebar = () => {
  sidebarVisible.value = !sidebarVisible.value;
};

// 响应式检查 - 添加一个计算属性判断是否为移动端
const isMobile = ref(false);
const checkMobile = () => {
  isMobile.value = window.innerWidth < 768;
};

// 初始化
onMounted(async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    await router.push('/login');
    return;
  }

  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    currentUser.value = payload.sub || payload.identity || payload.username;
    currentUserInitial.value = currentUser.value.charAt(0);

    await fetchUsers();
    initSocket();
  } catch (error) {
    console.error('解析token失败:', error);
    showNotification('登录信息无效，请重新登录');
    await router.push('/login');
  }

  // 添加响应式检测
  checkMobile();
  window.addEventListener('resize', checkMobile);
});

onUnmounted(() => {
  stopHeartbeat();
  if (socket.value) {
    socket.value.disconnect();
  }

  // 移除响应式检测
  window.removeEventListener('resize', checkMobile);
});

// 监听选中的用户变化
watch(selectedUser, (newVal) => {
  if (newVal) {
    loadMessages();
  }
});
</script>

<template>
  <div class="chat-bg">
    <div class="app-container">
      <ChatHeader
          :currentUser="currentUser"
          :currentUserInitial="currentUserInitial"
          @logout="showLogoutConfirmation = true"
          @toggle-sidebar="toggleSidebar"
          :showToggleButton="isMobile"
      />

      <main class="app-main">
        <Sidebar
            :visible="sidebarVisible"
            :users="filteredUsers"
            :onlineCount="onlineCount"
            :selectedUser="selectedUser"
            :searchQuery="searchQuery"
            @select-user="handleSelectUser"
            @update:searchQuery="searchQuery = $event"
        />

        <ChatArea
            :selectedUser="selectedUser"
            :messages="messages"
            :newMessage="newMessage"
            :formatTime="formatTime"
            @send-message="sendMessage"
            @update:newMessage="newMessage = $event"
        />
      </main>
    </div>

    <!-- 退出确认模态框 -->
    <div class="confirmation-modal" v-if="showLogoutConfirmation">
      <div class="modal-content">
        <h3>确定要退出登录吗?</h3>
        <p>退出后需要重新登录才能使用聊天功能</p>
        <div class="modal-buttons">
          <button class="btn" @click="showLogoutConfirmation = false">取消</button>
          <button class="btn btn-danger" @click="logout">确定退出</button>
        </div>
      </div>
    </div>

    <Notification v-if="notification.show" :message="notification.message" />
  </div>
</template>

<style scoped>
@import '@/assets/chat.css';
</style>
